package controller

import (
	"errors"
	"msems/logic"
	"strconv"

	"github.com/gin-gonic/gin"
)

const CtxUserIDKey = "userID"

var ErrorUserNotLogin = errors.New("用户未登录")  //用户未登录
var ErrorUserLevelErr = errors.New("用户权限不足") //用户权限不足

// GetCurrentUserID GetCurrentUser 获取token存储的用户id
func GetCurrentUserID(c *gin.Context) (userID int64, err error) {
	uid, ok := c.Get(CtxUserIDKey)
	if !ok {
		err = ErrorUserNotLogin
		return
	}
	userID, ok = uid.(int64) // 类型转换
	if !ok {
		err = ErrorUserNotLogin
		return
	}
	return
}

// 返回page和size用于分页
func getPageSize(c *gin.Context) (page, size int64) {
	pageSumStr := c.Query("page")
	pageSizeStr := c.Query("size")

	var (
		err error
	)
	page, err = strconv.ParseInt(pageSumStr, 10, 64)
	if err != nil {
		page = 1
	}
	size, err = strconv.ParseInt(pageSizeStr, 10, 64)
	if err != nil {
		size = 10
	}
	return
}

// GetUserLevelAndP 获取并判断权限
func GetUserLevelAndP(c *gin.Context, lev int) (id int64, err error) {
	//1.获取id
	id, err = GetCurrentUserID(c)
	if err != nil {
		return
	}
	//2.判断权限
	var level int
	level, err = logic.AdminLevel(id)
	if err != nil {
		return
	}
	if level <= lev {
		return id, nil
	} else {
		return id, ErrorUserLevelErr
	}
}
